<script lang="ts" setup>
import Statistics from './components/Statistics.vue'
import CourseConsultantSelect from './components/CourseConsultantSelect.vue'
import { EnrollmentApi } from '@/apis'
import type { TableInstanceColumns } from '@/components/ProTable/type'
import { useDictFilterOptions, useDownload, useForm, useTable } from '@/hooks'
import RangePicker from '@/components/common/RangePicker.vue'

defineOptions({
  name: 'EnrollIndex',
})
const router = useRouter()

const { form, resetForm } = useForm<EnrollmentApi.EnrollmentQuery>({
  studentId: undefined,
  classId: undefined,
  leadTeacherId: undefined,
  sellerId: undefined,
  status: undefined,
})
// 更多筛选
const filterCollapsed = ref<boolean>(true)

const {
  tableData,
  loading,
  pagination,
  search,
} = useTable(pagination => EnrollmentApi.getEnrollmentPage({ ...form, ...pagination }))

const columns: TableInstanceColumns[] = [
  { title: '报名编号', dataIndex: 'id', slotName: 'id', fixed: 'left', width: 185 },
  { title: '学生', dataIndex: 'student', slotName: 'student', width: 180 },
  { title: '班级', slotName: 'className', width: 360 },
  { title: '课次(上/退/总)', dataIndex: 'lessonStatus', slotName: 'lessonStatus', align: 'center', width: 140 },
  { title: '校区', dataIndex: 'campusName', align: 'center',  width: 120 },
  { title: '课程顾问', dataIndex: 'sellerName', width: 100, render: ({ record }) => record.sellerName || '-' },
  { title: '续报', slotName: 'renewalStatus', width: 80 },
  { title: '状态', dataIndex: 'status', slotName: 'enrollStatus', width: 100, filterable: {
    filters: useDictFilterOptions('EnrollmentStatusEnum'),
    multiple: true,
  } },
  // { title: '备注', dataIndex: 'remark', ellipsis: true, tooltip: true, width: 150, render: ({ record }) => record.remark || '-' },
  {
    title: '操作',
    slotName: 'action',
    width: 100,
    fixed: 'right',
  },
]

// 筛选
const onFilterChange = (dataIndex, filteredValues) => {
  form[dataIndex] = filteredValues
}

const onCreate = () => {
  router.push({ path: '/shop/enrollment/order/create' })
}

// 详情
const onDetail = (row) => {
  router.push({ path: '/education/class/enroll/detail', query: { id: row.id } })
}
const refresh = () => {
  resetForm()
  search()
}

const onExportExcel = async () => {
  useDownload(() => EnrollmentApi.exportEnrollmentList(form))
}

watch(() => form, (_) => {
  search()
}, { deep: true })

// 设置课程顾问
const CourseConsultantRef = ref<InstanceType<typeof CourseConsultantSelect>>()

const courseConsultantHandle = (enrollmentId: string) => {
  CourseConsultantRef.value?.open(enrollmentId)
}

// 转班调课
const gotoChangeClass = (record: EnrollmentApi.EnrollmentResp, changeType: string) => {
  router.push({
    path: '/education/class/change/create',
    query: {
      type: changeType,
      studentId: record.studentId,
      enrollmentId: record.id,
    },
  })
}

// 退班退课
const gotoCancelClass = (record: EnrollmentApi.EnrollmentResp, changeType: string) => {
  router.push({
    path: '/education/class/cancel/create',
    query: {
      type: changeType,
      studentId: record.studentId,
      enrollmentId: record.id,
    },
  })
}
</script>

<template>
  <ProPage title="报名记录" description="管理报名记录">
    <template #title-right>
      <Statistics />
    </template>
    <template #extra>
      <a-button v-permission="['shop:order:manage']" type="primary" @click="onCreate">
        <template #icon>
          <icon-plus />
        </template>
        <template #default>
          创建订单
        </template>
      </a-button>
    </template>
    <ProTable :data="tableData" :columns="columns" :loading="loading" :pagination="pagination" @refresh="search" @filter-change="onFilterChange">
      <template #search-panel>
        <a-space direction="vertical" size="small">
          <a-space>
            <label class="label">报名学生</label>
            <StudentSelect v-model="form.studentId" class="min-w-300px" />
            <CollapseButton v-model="filterCollapsed" />
          </a-space>
          <div v-show="filterCollapsed">
            <a-space wrap>
              <label class="label">班级筛选</label>
              <ClassSelect v-model="form.classId" class="min-w-300px" />
              <YearTermCascader v-model:class-year="form.classYear" v-model:term="form.term" class="min-w-120px" check-strictly />
              <DictSelect v-model="form.grade" type="select" code="Grade" placeholder="年级" class="min-w-120px!" multiple />
              <DictSelect v-model="form.subject" type="select" code="Subject" placeholder="科目" class="min-w-120px!" />
              <ClassTypeSelect v-model="form.classTypeId" placeholder="班型" class="!min-w-120px" />
            </a-space>

            <a-space wrap>
              <label class="label">其它条件</label>
              <DictSelect v-model="form.classCategory" type="button" code="ClassCategoryEnum" placeholder="类型" />
              <EmployeeSelect v-model="form.leadTeacherId" type="LEAD_TEACHER" placeholder="主讲老师" class="!w-150px" />
              <ClassroomCascader v-model:campus-id="form.campusId" v-model:classroom-id="form.classroomId" class="min-w-150px!" check-strictly />
              <RangePicker v-model:from="form.createDateFrom" v-model:to="form.createDateTo" :time="false"/>
            </a-space>
          </div>
        </a-space>
      </template>
      <template #toolbar-right>
        <a-button type="text" size="medium" @click="onExportExcel">
          <template #icon>
            <icon-download />
          </template>
          <span>导出</span>
        </a-button>
      </template>
      <template #id="{ record }">
        <div>
          <a-link @click="onDetail(record)">
            {{ record.id }}
          </a-link>
          <div class="pl-4px text-13px text-gray-5">
            {{ record.createTime }}
          </div>
        </div>
      </template>
      <template #className="{ record }">
        <CellClassInfo :id="record.classInfo.id" :name="record.classInfo.name" :lead-teacher-name="record.leadTeacherName" :assist-teacher-name="record.assistTeacherName" />
      </template>
      <template #student="{ record }">
        <CellStudent :id="record.studentId" :name="record.student.name" :gender="record.student.gender" :phone="record.student.parentPhone" />
      </template>
      <template #lessonStatus="{ record }">
        <span>{{ record.completedLessonCount }}/{{ record.cancelLessonCount }}/{{ record.enrollLessonCount }}</span>
      </template>
      <template #enrollStatus="{ record }">
        <CellDict code="EnrollmentStatusEnum" :value="record.status" />
      </template>
      <template #renewalStatus="{ record }">
        <CellStatus :status="record.isRenewal" on-text="" off-text="" />
      </template>
      <template #action="{ record }">
        <a-space v-permission="['edu:class-change:manage']">
          <a-dropdown trigger="hover">
            <a-link>
              操作
              <icon-down />
            </a-link>
            <template #content>
              <a-doption :disabled="record.status === 'CANCELED'" @click="courseConsultantHandle(record.id)">
                设置课程顾问
              </a-doption>
              <a-doption :disabled="record.status === 'CANCELED'" @click="gotoChangeClass(record, 'CHANGE_CLASS')">
                转班
              </a-doption>
              <a-doption :disabled="record.status === 'CANCELED'" @click="gotoChangeClass(record, 'CHANGE_LESSON')">
                调课
              </a-doption>
              <a-doption :disabled="record.status === 'CANCELED'" @click="gotoCancelClass(record, 'CANCEL_CLASS')">
                退班
              </a-doption>
              <a-doption :disabled="record.status === 'CANCELED'" @click="gotoCancelClass(record, 'CANCEL_LESSON')">
                退课
              </a-doption>
            </template>
          </a-dropdown>
        </a-space>
      </template>
    </ProTable>
    <CourseConsultantSelect ref="CourseConsultantRef" @change="search" />
  </ProPage>
</template>

<style lang="less" scoped>
.label {
  display: inline-block;
  width: 60px;
  text-align: right;
  flex-shrink: 0;
  margin-right: 10px;
}
</style>
